<template>
	<el-form :model="userForm" label-width="100px" ref="formRef" :rules="formRules" hide-required-asterisk>
		<el-form-item label="用户名" prop="username">
			<el-input v-model="userForm.username" placeholder="请输入用户名" />
		</el-form-item>
		<el-form-item label="密码" prop="password">
			<el-input type="password" v-model="userForm.password" placeholder="请输入密码"
				@keyup.enter="handleSubmit(formRef)" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="handleSubmit(formRef)" :icon="Check" :loading="loading">
				登录
			</el-button>
			<el-button @click="callback" :icon="Close">取消</el-button>
		</el-form-item>
	</el-form>
</template>

<script setup lang="ts">
import { login } from '@/api';
import type { UserType } from '@/types';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { Check, Close } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue';

const props = defineProps({
	callback: Function
})
const loading = ref(false)
const formRef = ref<FormInstance>()
const userForm = reactive<UserType>({
	username: '',
	password: ''
})
const formRules: FormRules = {
	username: [
		{ required: true, message: '用户名不可为空', trigger: 'blur' }
	],
	password: [
		{ required: true, message: '密码不可为空', trigger: 'blur' }
	]
}
const handleSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return
	await formEl.validate((valid, fields) => {
		if (valid) {
			loading.value = true
			login(userForm).then((res: any) => {
				if (res.code === 200) {
					ElMessage.success('登陆成功！')
					if (props.callback) {
						props.callback('login', true)
					}
				}
				loading.value = false
			})
		}
	})
}
</script>

<style lang="less" scoped>

</style>